/*
 * Vent_CreaComprobantes.java
 *
 * Created on 22 de agosto de 2008, 12:01 PM
 */

package administrador;


import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JOptionPane;

/**
 *
 * @author  daniel1split
 */
public class Vent_CreaComprobantes extends javax.swing.JFrame {
Conexion conexion;
Usuario user;
Parametros ventP;

//Parametro para guardar el codigo de la autorizacion:
int cod_auto;

    /** Creates new form Vent_CreaComprobantes */
    public Vent_CreaComprobantes(Conexion conexion,Usuario user,Parametros p) {
        this.conexion=conexion;
        this.user=user;
        ventP=p;
        
        
        
        initComponents();
        cargoComprobantes();
        setBounds(200,200,350,240);
        setVisible(true);
        refrescar();
        
        
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPanel1 = new javax.swing.JPanel();
        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();
        jLabel4 = new javax.swing.JLabel();
        txt_cod = new javax.swing.JTextField();
        txt_fecha = new javax.swing.JTextField();
        jButton1 = new javax.swing.JButton();
        cb_opcion = new javax.swing.JComboBox();
        txt_sec = new javax.swing.JFormattedTextField();
        txt_autorizacion = new javax.swing.JTextField();
        jLabel5 = new javax.swing.JLabel();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setName("Form"); // NOI18N

        org.jdesktop.application.ResourceMap resourceMap = org.jdesktop.application.Application.getInstance(administrador.AdministradorApp.class).getContext().getResourceMap(Vent_CreaComprobantes.class);
        jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder(null, resourceMap.getString("jPanel1.border.title"), javax.swing.border.TitledBorder.DEFAULT_JUSTIFICATION, javax.swing.border.TitledBorder.DEFAULT_POSITION, new java.awt.Font("Tahoma", 0, 11), resourceMap.getColor("jPanel1.border.titleColor"))); // NOI18N
        jPanel1.setFont(resourceMap.getFont("jPanel1.font")); // NOI18N
        jPanel1.setName("jPanel1"); // NOI18N

        jLabel1.setText(resourceMap.getString("jLabel1.text")); // NOI18N
        jLabel1.setName("jLabel1"); // NOI18N

        jLabel2.setText(resourceMap.getString("jLabel2.text")); // NOI18N
        jLabel2.setName("jLabel2"); // NOI18N

        jLabel3.setText(resourceMap.getString("jLabel3.text")); // NOI18N
        jLabel3.setName("jLabel3"); // NOI18N

        jLabel4.setText(resourceMap.getString("jLabel4.text")); // NOI18N
        jLabel4.setName("jLabel4"); // NOI18N

        txt_cod.setEditable(false);
        txt_cod.setText(resourceMap.getString("txt_cod.text")); // NOI18N
        txt_cod.setName("txt_cod"); // NOI18N
        txt_cod.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                txt_codActionPerformed(evt);
            }
        });

        txt_fecha.setEditable(false);
        txt_fecha.setText(resourceMap.getString("txt_fecha.text")); // NOI18N
        txt_fecha.setName("txt_fecha"); // NOI18N

        jButton1.setText(resourceMap.getString("jButton1.text")); // NOI18N
        jButton1.setName("jButton1"); // NOI18N
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        cb_opcion.setName("cb_opcion"); // NOI18N
        cb_opcion.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                cb_opcionActionPerformed(evt);
            }
        });

        txt_sec.setFormatterFactory(new javax.swing.text.DefaultFormatterFactory(new javax.swing.text.NumberFormatter(new java.text.DecimalFormat("#0"))));
        txt_sec.setText(resourceMap.getString("txt_sec.text")); // NOI18N
        txt_sec.setName("txt_sec"); // NOI18N
        txt_sec.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyTyped(java.awt.event.KeyEvent evt) {
                txt_secKeyTyped(evt);
            }
        });

        txt_autorizacion.setEditable(false);
        txt_autorizacion.setText(resourceMap.getString("txt_autorizacion.text")); // NOI18N
        txt_autorizacion.setName("txt_autorizacion"); // NOI18N

        jLabel5.setText(resourceMap.getString("jLabel5.text")); // NOI18N
        jLabel5.setName("jLabel5"); // NOI18N

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
                .addContainerGap(106, Short.MAX_VALUE)
                .addComponent(jButton1)
                .addContainerGap())
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addGap(19, 19, 19)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(jLabel4)
                    .addComponent(jLabel2)
                    .addComponent(jLabel1)
                    .addComponent(jLabel3)
                    .addComponent(jLabel5))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                    .addComponent(txt_autorizacion, javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(txt_sec, javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(cb_opcion, javax.swing.GroupLayout.Alignment.LEADING, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(txt_fecha, javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(txt_cod, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 190, Short.MAX_VALUE))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(txt_cod, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel1))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel3)
                    .addComponent(txt_fecha, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(8, 8, 8)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel2)
                    .addComponent(cb_opcion, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel4)
                    .addComponent(txt_sec, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(txt_autorizacion, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel5))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 20, Short.MAX_VALUE)
                .addComponent(jButton1)
                .addGap(28, 28, 28))
        );

        getContentPane().add(jPanel1, java.awt.BorderLayout.CENTER);

        pack();
    }// </editor-fold>//GEN-END:initComponents

private void txt_codActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_txt_codActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_txt_codActionPerformed

private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
// TODO add your handling code here:
    int codigo=Integer.valueOf(txt_cod.getText());
    String fecha=txt_fecha.getText();
    int secuencia=Integer.valueOf(this.txt_sec.getText());
    int opcion=cb_opcion.getSelectedIndex();
    String tipo=cb_opcion.getItemAt(opcion).toString();
    
    //Saco el ultimo numero de comprobante en funcion de los datos:
    int seleccion=cb_opcion.getSelectedIndex();
    String Documento=cb_opcion.getItemAt(seleccion).toString();
    ResultSet resp=conexion.consultarBase("SELECT max(num_secuencia) FROM tipo_comprobante where nombre like '"+Documento+"';");
    int secuenciaActual=0;
    try {
        resp.beforeFirst();
        resp.next();
        secuenciaActual=resp.getInt(1);
        
    } catch (SQLException ex) {
        Logger.getLogger(Vent_CreaComprobantes.class.getName()).log(Level.SEVERE, null, ex);
    }
    
    if (secuencia <= secuenciaActual) {
        JOptionPane.showMessageDialog(this,"No se puede crear una secuencia con un valor menor al ultimo numero se secuencia asignado","Informacion",JOptionPane.INFORMATION_MESSAGE);
    } else {
        
        boolean exito = conexion.insertarDatosR("insert into tipo_comprobante values(" + codigo + ",'" + tipo + "','" + fecha + "'," + secuencia + ","+cod_auto+")");
        if (exito) {
            ventP.refrescar();
            refrescar();
            dispose();
        } else {
            JOptionPane.showMessageDialog(this, "Existen problemas en la insercion de Datos", "Informacion", JOptionPane.INFORMATION_MESSAGE);
        }
    }

    
    
    
    
}//GEN-LAST:event_jButton1ActionPerformed

private void cb_opcionActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cb_opcionActionPerformed
// TODO add your handling code here:
    
    
}//GEN-LAST:event_cb_opcionActionPerformed

private void txt_secKeyTyped(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txt_secKeyTyped
// TODO add your handling code here:
    char c = evt.getKeyChar();
    if (!(Character.isDigit(c) || (c == java.awt.event.KeyEvent.VK_BACK_SPACE) || (c == java.awt.event.KeyEvent.VK_DELETE))) {
          getToolkit().beep();
          evt.consume();
          
    }
    
}//GEN-LAST:event_txt_secKeyTyped

public void cargoComprobantes(){
//Cargo en el Combo unicamente los Comprobantes que no se han creado 
//y establecido sus secuenciales para la autorizacion actual:
//De esta manera nunca se repetiran los comprobantes para una autorizacion
    cb_opcion.removeAllItems();
    String[] comprobantesPosibles={"Factura","Nota de Venta","Nota de Credito","Nota de Debito","Factura de Compras","Devolucion en Compras"};
    int tamano=comprobantesPosibles.length;
    for(int i=0;i<tamano;i++){
        ResultSet resp=conexion.consultarBase("select max(cod_auto) from autorizacion ;");
        int autorizacionActual=0;
            try {
                resp.beforeFirst();
                resp.next();
                autorizacionActual=resp.getInt(1);
               //System.out.println("El codigo de Autorizacion Actual es:"+autorizacionActual+" comprobante:"+comprobantesPosibles[i]);
                resp=conexion.consultarBase("SELECT * FROM tipo_comprobante t where nombre like '"+comprobantesPosibles[i]+"' and cod_autorizacion="+autorizacionActual+";");
                int datos=conexion.obtenerFilas(resp);
               //System.out.println("Las filas obtenidas son:"+datos);
                if(datos==0){
                cb_opcion.addItem(comprobantesPosibles[i]);
                }
                
                
                
                
            } catch (Exception ex) {
                Logger.getLogger(Vent_CreaComprobantes.class.getName()).log(Level.SEVERE, null, ex);
            }
        
        
        
    
    }
    

    
    
}



public void refrescar(){
     
    int codigo=0;
        try {
            java.sql.ResultSet resp = conexion.consultarBase("select MAX(idcodigo) from tipo_comprobante;");
            resp.beforeFirst();
            resp.next();
            codigo=resp.getInt(1)+1;
        } catch (SQLException ex) {
            Logger.getLogger(Vent_CreaComprobantes.class.getName()).log(Level.SEVERE, null, ex);
        }
        txt_fecha.setText(new java.sql.Date(System.currentTimeMillis()).toString());
        txt_cod.setText(String.valueOf(codigo));
        txt_sec.setText("");
        
        //Saco los parametros para la autorizacion:
        pongoAutorizacion();
}

public void pongoAutorizacion(){
int seleccion=cb_opcion.getSelectedIndex();
String Documento;
try{
    Documento=cb_opcion.getItemAt(seleccion).toString();
}catch (java.lang.NullPointerException ex) {
JOptionPane.showMessageDialog(this,"No existen Documento para Asignar Secuencias","Informacion",JOptionPane.INFORMATION_MESSAGE);
}         



ResultSet resp=conexion.consultarBase("SELECT numero,cod_auto FROM autorizacion a order by cod_auto;");
    try {
        resp.last();
        resp.previous();
        resp.next();
        long autorizacion=resp.getLong(1);
        cod_auto=resp.getInt(2);
        txt_autorizacion.setText(String.valueOf(autorizacion));
    }catch (SQLException ex) {
        Logger.getLogger(Vent_CreaComprobantes.class.getName()).log(Level.SEVERE, null, ex);
    }


}


    /**
    * @param args the command line arguments
    */

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JComboBox cb_opcion;
    private javax.swing.JButton jButton1;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JTextField txt_autorizacion;
    private javax.swing.JTextField txt_cod;
    private javax.swing.JTextField txt_fecha;
    private javax.swing.JFormattedTextField txt_sec;
    // End of variables declaration//GEN-END:variables

}
